package com.itheima.spring.bestpractive.common.advice;


import com.itheima.spring.bestpractive.common.exception.BizException;
import com.itheima.spring.bestpractive.common.myResult.R;
import com.itheima.spring.bestpractive.common.myResult.REnum;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * @author: HZY
 * @date: 2025/6/20 15:59
 * @Content:
 */
@RestControllerAdvice
public class MYControllerAdvice {

    @ExceptionHandler(BizException.class)
    public R<Object> handleBizException(BizException e) {
        return R.fail(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        Map<String, String> errors = new HashMap<>();
        e.getBindingResult().getFieldErrors().forEach(fieldError -> {
            errors.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return R.of(REnum.PARAM_ERROR, errors);
    }

//    @ExceptionHandler(MyBatisSystemException.class)
//    public R<Object> handleMyBatisSystemException(MyBatisSystemException e) {
//        return R.fail(REnum.SERVER_SQL_ERROR);
//    }

//    @ExceptionHandler(RuntimeException.class)
//    public R<Object> handleRuntimeException(RuntimeException e) {
//        return R.of(REnum.SERVER_ERROR,e);
//    }
}
